<template>
  <div class="app-container">
    <el-tabs v-model="activeTab" type="card">
      <!-- 文件上传测试 -->
      <el-tab-pane label="文件上传" name="file">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>FileUpload 组件测试</span>
              <el-tag type="primary" size="small">通用文件上传</el-tag>
            </div>
          </template>

          <div class="demo-section">
            <h4>组件特点：</h4>
            <ul class="feature-list">
              <li>📁 支持拖拽和点击选择文件</li>
              <li>🔄 小于50MB自动普通上传，大于50MB自动分片上传</li>
              <li>☁️ 支持前端直传（MinIO/阿里云/腾讯云/AWS）</li>
              <li>📊 实时上传进度显示</li>
              <li>🔢 支持多文件上传和数量限制</li>
              <li>🛡️ 文件类型和大小验证（基于存储配置）</li>
              <li>⚙️ 文件大小限制自动从存储配置获取</li>
            </ul>

            <!-- 组件配置 -->
            <div class="config-section">
              <el-form :model="fileConfig" label-width="120px" inline>
                <el-form-item label="最大文件数：">
                  <el-input-number v-model="fileConfig.limit" :min="1" :max="10" size="small"/>
                </el-form-item>
              </el-form>
            </div>

            <!-- FileUpload 组件 -->
            <FileUpload
                v-model="uploadedFiles"
                :limit="fileConfig.limit"
                @upload-success="handleFileUploadSuccess"
                @upload-error="handleFileUploadError"
                @upload-progress="handleFileUploadProgress"
            />

          </div>
        </el-card>
      </el-tab-pane>

      <!-- 图片上传测试 -->
      <el-tab-pane label="图片上传" name="image">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>ImageUpload 组件测试</span>
              <el-tag type="success" size="small">专为图片优化</el-tag>
            </div>
          </template>

          <div class="demo-section">
            <h4>组件特点：</h4>
            <ul class="feature-list">
              <li>🖼️ 专门针对图片格式优化</li>
              <li>🔍 内置图片预览功能</li>
              <li>🎯 支持网格和列表两种布局</li>
              <li>📸 自动生成缩略图</li>
              <li>⚡ 自动上传模式</li>
              <li>🗜️ 智能图片压缩，保证清晰度</li>
              <li>📊 压缩率显示和状态提示</li>
            </ul>

            <!-- 组件配置 -->
            <div class="config-section">
              <el-form :model="imageConfig" label-width="120px" inline>
                <el-form-item label="最大图片数：">
                  <el-input-number v-model="imageConfig.maxCount" :min="1" :max="10" size="small"/>
                </el-form-item>
                <el-form-item label="布局模式：">
                  <el-radio-group v-model="imageConfig.layout" size="small">
                    <el-radio label="grid">网格</el-radio>
                    <el-radio label="list">列表</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="启用压缩：">
                  <el-switch v-model="imageConfig.enableCompress" size="small"/>
                </el-form-item>
                <el-form-item label="压缩模式：" v-if="imageConfig.enableCompress">
                  <el-radio-group v-model="imageConfig.compressMode" size="small">
                    <el-radio label="quality">质量压缩</el-radio>
                    <el-radio label="size">大小压缩</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="压缩质量：" v-if="imageConfig.enableCompress && imageConfig.compressMode === 'quality'">
                  <el-slider 
                    v-model="imageConfig.compressQuality" 
                    :min="0.1" 
                    :max="1" 
                    :step="0.1" 
                    style="width: 120px"
                    size="small"
                  />
                  <span class="slider-label">{{ (imageConfig.compressQuality * 100).toFixed(0) }}%</span>
                </el-form-item>
                <el-form-item label="目标大小：" v-if="imageConfig.enableCompress && imageConfig.compressMode === 'size'">
                  <el-input-number 
                    v-model="imageConfig.maxFileSize" 
                    :min="10" 
                    :max="2048" 
                    :step="10"
                    size="small"
                    style="width: 120px"
                  />
                  <span class="slider-label">KB</span>
                  <el-tooltip content="算法会智能缩放尺寸和调整质量，尽力压缩到目标大小" placement="top">
                    <el-icon style="margin-left: 8px; color: #409eff;"><QuestionFilled /></el-icon>
                  </el-tooltip>
                </el-form-item>
              </el-form>
              
              <!-- 路径配置区域 -->
              <div class="path-config">
                <h5>📁 路径配置</h5>
                <el-form :model="imageConfig" label-width="120px" inline>
                  <el-form-item label="上传目录：">
                    <el-input 
                      v-model="imageConfig.uploadDir" 
                      placeholder="请输入上传目录路径" 
                      size="small"
                      style="width: 200px"
                    />
                    <el-tooltip content="支持多级目录，如：images/avatar, documents/2023" placement="top">
                      <el-icon style="margin-left: 8px; color: #409eff;"><QuestionFilled /></el-icon>
                    </el-tooltip>
                  </el-form-item>
                  <el-form-item label="存储配置：">
                    <el-select 
                      v-model="imageConfig.configId" 
                      placeholder="自动选择默认配置" 
                      size="small"
                      style="width: 180px"
                      clearable
                    >
                      <el-option 
                        v-for="config in storageConfigs" 
                        :key="config.configId" 
                        :label="config.configName"
                        :value="config.configId"
                      />
                    </el-select>
                  </el-form-item>
                </el-form>
              </div>
            </div>

            <!-- ImageUpload 组件 -->
            <ImageUpload
                v-model="uploadedImages"
                :max-count="imageConfig.maxCount"
                :layout="imageConfig.layout"
                :enable-compress="imageConfig.enableCompress"
                :compress-mode="imageConfig.compressMode"
                :compress-quality="imageConfig.compressQuality"
                :max-file-size-kb="imageConfig.maxFileSize"
                :min-compress-size="imageConfig.minCompressSize"
                :default-dir="imageConfig.uploadDir"
                :default-config-id="imageConfig.configId"
                @upload-success="handleImageUploadSuccess"
                @upload-error="handleImageUploadError"
                @preview="handleImagePreview"
                @remove="handleImageRemove"
                @compress-start="handleImageCompressStart"
                @compress-end="handleImageCompressEnd"
            />
          </div>
        </el-card>
      </el-tab-pane>

      <!-- 分片上传演示 -->
      <el-tab-pane label="分片上传" name="chunk">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>分片上传演示</span>
              <el-tag type="warning" size="small">大文件上传</el-tag>
            </div>
          </template>

          <div class="demo-section">
            <el-alert title="分片上传说明" type="info" :closable="false" show-icon>
              <p>分片上传适用于大文件（>50MB），将文件分割成小块并发上传，提高上传成功率。</p>
              <p>FileUpload 组件会自动判断文件大小，超过50MB时自动启用分片上传。</p>
              <p><strong>新增重试机制：</strong>每个分片失败后会自动重试3次，采用指数退避策略。</p>
              <p><strong>智能错误处理：</strong>错误率超过50%时会自动停止上传，避免无效重试。</p>
            </el-alert>

            <!-- 大文件上传演示 -->
            <div class="chunk-demo">
              <h4>大文件上传演示：</h4>
              <FileUpload :limit="1" @upload-success="handleChunkUploadSuccess" @upload-error="handleChunkUploadError" @upload-progress="handleChunkUploadProgress"/>
            </div>
          </div>
        </el-card>
      </el-tab-pane>
    </el-tabs>

  </div>
</template>

<script setup name="FileUploadTest">
import {computed, onMounted, reactive, ref} from 'vue'
import {ElMessage} from 'element-plus'
import { QuestionFilled } from '@element-plus/icons-vue'
// 移除配置加载导入，让组件自行处理
import FileUpload from "@/components/FileUpload/index.vue"
import ImageUpload from "@/components/ImageUpload/index.vue"
import {getDefaultConfigId} from '@/store/modules/fileConfig'
import {getImageUrl} from '@/utils/upload-utils'
import { listStorageConfig } from '@/api/filemanager/storage'

// 当前选中的标签页
const activeTab = ref('file')

// 存储配置
const storageConfigs = ref([])

// 文件上传配置
const fileConfig = reactive({
  limit: 5
})

// 图片上传配置
const imageConfig = reactive({
  maxCount: 5,
  layout: 'grid',
  enableCompress: true,
  compressMode: 'quality',   // 压缩模式: 'quality'(质量压缩) | 'size'(大小压缩)
  compressQuality: 0.2,      // 质量压缩参数 (0.1-1.0)
  maxFileSize: 100,          // 大小压缩参数 (KB)
  minCompressSize: 100,
  uploadDir: null,  // 上传目录
  configId: null             // 存储配置ID
})

// 上传数据
const uploadedFiles = ref([])
const uploadedImages = ref([])


// 工具函数
function formatFileSize(bytes) {
  if (!bytes) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 文件上传事件处理
function handleFileUploadSuccess(event) {
  ElMessage.success(`文件 ${event.file.name} 上传成功`)
}

function handleFileUploadError(event) {
  ElMessage.error(`文件 ${event.file.name} 上传失败`)
}

function handleFileUploadProgress(event) {
  // 可以在这里处理进度，目前仅显示消息
}

// 图片上传事件处理
function handleImageUploadSuccess(event) {
  ElMessage.success(`图片 ${event.file.name} 上传成功`)

  // 将上传成功的图片添加到预览列表中
  if (event.image) {
    const existingIndex = uploadedImages.value.findIndex(img => img.id === event.image.id)
    if (existingIndex === -1) {
      uploadedImages.value.push(event.image)
    }
  }
}

function handleImageUploadError(event) {
  ElMessage.error(`图片 ${event.file.name} 上传失败`)
}

function handleImagePreview(event) {
  // 图片预览事件处理
}

function handleImageRemove(event) {
  // 从预览列表中移除对应的图片
  if (event.index >= 0 && event.index < uploadedImages.value.length) {
    uploadedImages.value.splice(event.index, 1)
  }
}

// 图片压缩事件处理
function handleImageCompressStart(event) {
  console.log('开始压缩图片:', event.file.name)
}

function handleImageCompressEnd(event) {
  const { originalFile, compressedFile, originalSize, newSize, compressRatio } = event
  console.log(`图片压缩完成: ${originalFile.name}`)
  console.log(`原始大小: ${formatFileSize(originalSize)}`)
  console.log(`压缩后大小: ${formatFileSize(newSize)}`)
  console.log(`压缩率: ${compressRatio}%`)
  
  const mode = imageConfig.compressMode === 'quality' ? '质量压缩' : '大小压缩'
  ElMessage.success(`${originalFile.name} ${mode}完成，节省 ${compressRatio}% 空间`)
}


// 分片上传事件处理
function handleChunkUploadSuccess(event) {
  ElMessage.success(`大文件 ${event.file.name} 分片上传成功`)
}

function handleChunkUploadError(event) {
  ElMessage.error(`大文件 ${event.file.name} 分片上传失败`)
}

function handleChunkUploadProgress(event) {
  // 分片上传进度处理
}

// 工具函数
function getFileName(filePath) {
  if (typeof filePath === 'string') {
    return filePath.split('/').pop()
  }
  return filePath.name || '未知文件'
}

async function copyUrl(file) {
  try {
    let url = ''
    let filePath = ''

    // 提取文件路径
    if (typeof file === 'string') {
      filePath = file
    } else if (file && typeof file === 'object') {
      // 优先使用后端返回的完整URL
      if (file.url && file.url.startsWith('http')) {
        url = file.url
      } else {
        filePath = file.filePath || file.url
      }
    }

    // 如果没有完整URL，通过API获取
    if (!url && filePath) {
      const configId = await getDefaultConfigId()
      url = await getImageUrl(filePath, configId)
    }

    if (url) {
      await navigator.clipboard.writeText(url)
      ElMessage.success('文件URL已复制到剪贴板')
    } else {
      ElMessage.error('无法获取文件URL')
    }
  } catch (error) {
    console.error('复制URL失败:', error)
    ElMessage.error('复制URL失败')
  }
}


// 加载存储配置
async function loadStorageConfigs() {
  try {
    const response = await listStorageConfig()
    storageConfigs.value = response.rows || []
    
    // 如果没有选择配置，自动选择默认配置
    if (!imageConfig.configId && storageConfigs.value.length > 0) {
      const defaultConfigId = await getDefaultConfigId(storageConfigs.value)
      imageConfig.configId = defaultConfigId
    }
  } catch (error) {
    console.error('加载存储配置失败:', error)
    ElMessage.warning('加载存储配置失败，请检查网络连接')
  }
}

onMounted(() => {
  console.log('上传测试页面已挂载')
  // 加载存储配置
  loadStorageConfigs()
})
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
}

.demo-section {
  padding: 20px 0;
}

.demo-section h4 {
  margin-bottom: 10px;
  color: #303133;
}

.feature-list {
  margin: 0 0 20px 0;
  padding: 0;
  list-style: none;
}

.feature-list li {
  padding: 6px 0;
  font-size: 14px;
  color: #606266;
}

.config-section {
  background-color: #f8f9fa;
  padding: 16px;
  border-radius: 6px;
  margin-bottom: 20px;

  .slider-label {
    margin-left: 8px;
    font-size: 12px;
    color: #409eff;
    font-weight: 500;
    min-width: 35px;
    display: inline-block;
  }

  .path-config {
    margin-top: 16px;
    padding-top: 16px;
    border-top: 1px solid #e4e7ed;

    h5 {
      margin: 0 0 12px 0;
      color: #303133;
      font-size: 14px;
      font-weight: 500;
    }
  }
}



.chunk-demo {
  margin-top: 20px;
  padding: 20px;
  background-color: #fff7e6;
  border-radius: 6px;
  border: 1px solid #ffd591;
}

.chunk-demo h4 {
  margin-bottom: 15px;
  color: #d46b08;
}

</style>
